﻿using System.Net.Sockets;
using System.Net;
using System.Text;

namespace TcpMultPortServer
{
    internal class Program
    {
        static int startPort = 6001;
        static int portNum = 20;

        static void Main(string[] args)
        {
            for (int i = 0; i < portNum; i++) {
                Thread t = new Thread(ServerThread);
                t.IsBackground = true;
                t.Start(startPort + i);
            }

            Console.WriteLine("Hello, World!");

            Thread.Sleep(10 * 1000);//10秒延时
        }


        private static void ServerThread(object? objPort) {
            int port = (int)(objPort==null?6001:objPort);
            //string cmd = "AT+STACH0=6,2,2,1000000\r\n";
            //string cmd = "AT+STACH0=6,3,3,1000000\r\n";
            //string cmd = "AT+STACH0=6,4,4,1000000\r\n";
            string cmd = "AT+STACH0=0\r\n";

            //IPAddress.Any为所有网卡，
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
            //创建listens是传入的套接字。
            Socket listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.NoDelay = true;
            //绑定端口
            listenSocket.Bind(localEndPoint);
            //挂起的连接队列的最大长度。
            listenSocket.Listen(1000);
            Console.WriteLine("port:" + port.ToString() + "  Server Accept...");
            Socket clientSocket = listenSocket.Accept();
            clientSocket.Send(Encoding.ASCII.GetBytes(cmd));
            byte[] buffer = new byte[1024];
            int size = 0;
            size = clientSocket.Receive(buffer);
            if(size > 0)Console.WriteLine("接收到的信息为:" + Encoding.ASCII.GetString(buffer, 0, size));
            Console.WriteLine("准备关闭<port:{0}>连接",port);
            clientSocket.Close();
            listenSocket.Close();
        }


    }
}